package com.itheima.htmo_01.controller;

import cn.hutool.core.bean.BeanUtil;
import com.itheima.htmo_01.dto.RegisterUserDTO;
import com.itheima.htmo_01.pojo.Result;
import com.itheima.htmo_01.pojo.User;
import com.itheima.htmo_01.service.UserService;
import com.itheima.htmo_01.utils.JwtUtil;
import com.itheima.htmo_01.utils.Md5Util;
import jakarta.annotation.Resource;
import jakarta.validation.constraints.Pattern;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;


@CrossOrigin(origins = "*")
@RestController
public class LoginController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    public Result<String> login( String username, String password){
//        根据用户名查询用户
        User loginUser=userService.findByUserName(username);

//        判断该用户是否存在
        if(loginUser==null){
            return Result.error("用户名错误");
        }
//        判断密码是否正确
        if(Md5Util.getMD5String(password).equals(loginUser.getPassword())){
//         登录成功

            Map<String,Object> claims=new HashMap<>();
            claims.put("id",loginUser.getId());
            claims.put("username",loginUser.getUsername());
            String token = JwtUtil.genToken(claims);
            return Result.success(token);
        }

        return Result.error("密码错误");
    }

    @PostMapping("/register")
    public Result register(@RequestBody RegisterUserDTO registerUserDTO) {

        //查询用户
        User u = userService.findByUserName(registerUserDTO.getUsername());
        if (u == null) {
            //没有占用
            //注册
            userService.register(registerUserDTO);
            return Result.success();
        } else {
            //占用
            return Result.error("用户名已被占用");
        }


    }
}
